package second.codeTop.package1;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @ClassName LC1
 * @description:
 * @author: 荣燊
 * @create: 2022-03-28 16:06
 **/
public class LC1 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
//        Arrays.sort(nums);
//        for (int i : nums) {
//            System.out.println(i);
//        }
        int[] ints = twoSum(nums, 9);
        System.out.println(ints);
    }

    public static int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];
        for (int i=0; i<nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
                break;
            }
            map.put(nums[i], i);
        }
        return res;
    }

    // 有序的话，倒是可以这么做
    public static int[] twoSum1(int[] nums, int target) {
        Arrays.sort(nums);
        int i = 0;
        int j = nums.length-1;
        int[] res = new int[2];
        while (i < j) {
            int temp = nums[i] + nums[j];
            if (temp > target) {
                j--;
            }
            if (temp < target) {
                i++;
            }
            if (temp == target) {
                res[0] = i;
                res[1] = j;
                break;
            }
        }
        return res;
    }
}
